package com.ahucoding.rocket.mcpserver.service;

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Service
public class BookService {


    public record Book(String isbn, String title, List<String> authorName) {
    }

    public static final List<Book> BOOKS = new ArrayList<>();

    static {
        final Book book = new Book("ISBN-88888888888", "SpringAI教程", List.of("红专写的书"));
        final Book book1 = new Book("ISBN-88888777777", "Linux教程", List.of("linus写的书"));
        BOOKS.add(book);
        BOOKS.add(book1);
    }

    @Tool(description = "通过标题查询书本")
    public List<Book> getBooks(String title) {

        System.out.println("getBooks title:" + title);

        for (Book book : BOOKS) {
            if (book.title.toLowerCase().contains(title.toLowerCase()) || title.toLowerCase().contains(book.title.toLowerCase())) {
                return List.of(book);
            }
        }

        return List.of(new Book("no isbn", "no title", List.of("no author")));
    }

    @Tool(description = "通过作者查询书本")
    public List<Book> getBookTitlesByAuthor(String authorName) {
        AtomicReference<List<Book>> title = new AtomicReference<>();
        for (Book book : BOOKS) {
            book.authorName.forEach(name -> {
                if (name.toLowerCase().contains(authorName.toLowerCase()) || authorName.toLowerCase().contains(name.toLowerCase())) {
                    title.set(List.of(book));
                }
            });
        }

        return title.get();
    }

    @Tool(description = "通过isbn查询书本")
    public List<Book> getBookAuthorByIsbn(String isbn) {
        System.out.println("getBookAuthorByIsbn isbn:" + isbn);
        for (Book book : BOOKS) {
            if (book.isbn.toLowerCase().contains(isbn.toLowerCase()) || isbn.toLowerCase().contains(book.isbn.toLowerCase())) {
                return List.of(book);
            }
        }

        return List.of(new Book("no isbn", "no title", List.of("no author")));
    }

}
